<template>
	<popup closeable mode="bottom" :top="24" :popup="false" v-model="value" length="auto" @close="close">
		<view ref="calendar" class="calendar">
			<slot></slot>
			<view class="calendar-header" v-if="needBlank">
				<span class="headerTxt">出行日期</span>
				<span class="headerDate">{{headerDate}}</span>
			</view>
			<!-- 月份面板 -->
			<view class="month">
				<view class="week-day" :class="{active: active===index}" @click="changeMonth(month,index)"
					v-for="(month,index) in allMonthData" :key="index">
					<view class="month-text">{{month.month}}月</view>
					<!-- <view class="price" v-if="showPrice">￥3280起</view> -->
				</view>
			</view>
			<!-- 星期面板 -->
			<view class="week">
				<view class="week-day weekend-day">日</view>
				<view class="week-day">一</view>
				<view class="week-day">二</view>
				<view class="week-day">三</view>
				<view class="week-day">四</view>
				<view class="week-day">五</view>
				<view class="week-day weekend-day">六</view>
			</view>
			<!-- 每月展示内容 -->
			<view class="calendar-content" ref="calendarWraper">
				<scroll-view :scroll-into-view="defaultOpenDate" style="height:70%" :scroll-y="true">
					<view class="calendar-content-item" v-for="(month,index) in allMonthData"
						:id="'calendar-content-item'+(index+1)" :key="index" v-show="active==index">
						<ul class="calendar-content-day">
							<li class="day-item" @click="selectDate(month, day)" v-for="(day,ii) in month.date"
								:class="{holiday: day.isWeekend, disable: day.isDisable,scope:isScope(month,day),lasts:isLast(month.date.length,ii)}"
								:key="ii">
								<view class="day-item-content" :class="{InRange: day.isShow&&day.dates,CheckInDate: day.isCheckInDate&&day.dates,
									themeBackground: day.isCheckInDate || day.isCheckOutDate,
									CheckOutDate: day.isCheckOutDate,single:day.isCheckInDate && pattern==='single'&&day.dates}">
									<!-- <p class="day-item-stock" v-if="day.stock>0&&day.dates">
										{{day.stock>99?'充足':day.stock+'位'}}
									</p> -->
									<!-- <p class="day-item-stock" v-if="day.stock===0&&day.dates && day.id">已售罄</p> -->
									<p class="day-item-num">{{day.showDate}}</p>
									<span v-if="day.isShow&&day.dates && day.saleSettlementPrice"
										class="day-item-price">￥{{day.saleSettlementPrice}}</span>
									<p class="check-block holiday" v-if="day.isCheckInDate & pattern!=='single'">
										{{startText}}
									</p>
									<p class="check-block holiday" v-if="day.isCheckOutDate & pattern!=='single'">
										{{endText}}
									</p>
									<p class="restDay" v-if="day.isRestDay && !day.isWeekend">休</p>
								</view>
							</li>
						</ul>
						<view class="calendar-content-division"></view>
					</view>
				</scroll-view>
				<slot name="number"></slot>
			</view>
			<!-- 底部按钮 -->
			<view class="calendar-foot">
				<!-- <view class="service">
					<image :src="require('@/static/public/service.png')" mode=""></image>
					客服
				</view> -->
				<view class="info font-weight-500">
					<p class="font-13 color-999">出行日期</p>
					<p class="color-555">
						{{headerDate}}
					</p>
				</view>
				<view @click="determine" class="btn">确定</view>
			</view>
		</view>
	</popup>
</template>
<script>
	import popup from './popup.vue'
	import moment from 'dayjs'
	export default {
		components: {
			popup
		},
		props: {
			// 通过双向绑定控制组件的弹出与收起
			value: {
				type: Boolean,
				default: false
			},
			//展示每月最低价
			showPrice: {
				type: Boolean,
				default: true
			},
			//当前选中日期
			info: {
				type: [Object, String],
				default () {
					return {
						checkInDate: '',
						checkOutDate: '',
						startDate: '', // 门票 默认选中日期
						defaultOpenDate: '' // 默认打开日历月份
					}
				}
			},
			//日历数组
			range: {
				type: Array,
				default () {
					return []
				}
			},
			// 只有开始和结束时间
			rangeObj: {
				type: Object,
				default () {
					return {
						start: '',
						end: ''
					}
				}
			},
			//单选或多选
			pattern: {
				type: String,
				default: 'section'
			},
			//入住与离店的文案
			startText: {
				type: String,
				default: '入住'
			},
			endText: {
				type: String,
				default: '离店'
			}
		},
		data() {
			return {
				active: 0,
				needBlank: false,
				isCheckComplete: true,
				isRange: false,
				inside: {
					checkInDate: '',
					checkOutDate: '',
					saleSettlementPrice: '',
					stock: ''
				},
				checkInDate: {
					date: {
						isCheckInDate: false
					}
				},
				checkOutDate: {},
				allMonthData: [],
				rangs: [],
				now: '',
			}
		},
		computed: {
			//入住时间格式化
			currentStart() {
				return new Date(this.inside.checkInDate.replace(/-/gm, '/'))
			},
			//离店时间格式化
			currentEnd() {
				return new Date(this.inside.checkOutDate.replace(/-/gm, '/'))
			},
			//打开日历时滚动到当前月份
			defaultOpenDate() {
				let scrollIndex = 1
				let startMonth = this.info.defaultOpenDate ? this.info.defaultOpenDate.split('-')[1] : ''
				if (this.allMonthData[0] && startMonth) {
					scrollIndex = (startMonth - this.allMonthData[0].month) + 1
					scrollIndex = scrollIndex <= 0 ? scrollIndex + 12 : scrollIndex
				}
				return 'calendar-content-item' + scrollIndex
			},
			headerDate() {
				return this.inside.checkInDate?moment(this.currentStart).format('YYYY年MM月D号'):''
			}
		},
		mounted() {
			this.initDate()
			if (this.pattern === 'section') { // 酒店的 入住-离店
				this.inside.checkInDate = this.info.checkInDate
				this.inside.checkOutDate = this.info.checkOutDate
			} else { // pattern === 'single'
				this.checkInDate.date.isCheckInDate = true
				this.inside.checkInDate = this.info.checkInDate
			}
		},
		watch: {
			rangeObj: {
				handler(val) {
					this.initDate()
				},
				deep: true
			},
			info: {
				handler(val) {
					if (val.checkInDate) {
						this.inside.checkInDate = this.info.checkInDate
						this.initDate()
					}
				},
				deep: true
			},
			range(val) {
				this.initDate()
			},
		},
		methods: {
			//关闭日历
			close() {
				this.$emit('on-close')
			},
			async initDate() {
				if (!this.now) {
					let sysTime = (new Date()).getTime()
					this.now = sysTime
				}
				this.initCalendar()
			},
			initCalendar() {
				// 需要显示节假日需要更新节假日信息，没有找到合适的节假日接口，这部分以后更新
				this.getAllMonthData(4)
				let checkInMonth = this.info.checkInDate.split('-')[1]
				let checkInDate = this.info.checkInDate.split('-')[2]
				for (let month of this.allMonthData) {
					let newmonth = '0' + (month.month)
					if ((newmonth + '') === checkInMonth) {
						for (let date of month.date) {
							if ((date.showDate + '') === checkInDate) {
								date.isCheckInDate = true
								this.checkInDate = {
									month: month,
									date: date
								}
								break
							}
						}
					}
					if (this.pattern === 'section') {
						let checkOutMonth = this.info.checkOutDate.split('-')[1]
						let checkOutDate = this.info.checkOutDate.split('-')[2]
						if ((newmonth + '') === checkOutMonth) {
							for (let date of month.date) {
								if ((date.showDate + '') === checkOutDate) {
									date.isCheckOutDate = true
									this.checkOutDate = {
										month: month,
										date: date
									}
									break
								}
							}
							break
						}
					}
				}
			},
			isLast(length, i) {
				let linage = parseInt(length / 7)
				if ((i + 1) / 7 > linage) {
					return true
				} else {
					return false
				}
			},
			isScope(month, day) {
				let date = new Date(month.year + '/' + month.month + '/' + day.dates)
				return this.currentStart < date && date < this.currentEnd && this.isCheckComplete
			},
			//选中日期
			determine() {
				this.$emit('on-determine', this.inside)
			},
			getMonthData(year, month) {
				let ret = []
				if (!year || !month) {
					let today = new Date(this.now)
					year = today.getFullYear()
					month = today.getMonth() + 1
				}
				let firstDay = new Date(year, month - 1, 1)
				let firstWeekDay = firstDay.getDay()
				let firstDayWeekDay = firstDay.getDay()
				let preMonthDayCount = firstDayWeekDay - 1
				let lastDay = new Date(year, month, 0)
				let lastDate = lastDay.getDate()
				for (let i = 0; i < 38; i++) {
					let date = i - preMonthDayCount
					let showDate = date
					if (date <= 0) {
						showDate = ''
					} else if (date > lastDate) {
						continue
					}
					let isWeekend = false
					if ((showDate + firstWeekDay) % 7 === 0 || (showDate + firstWeekDay) % 7 === 1) {
						isWeekend = true
					}
					let isRestDay = false
					ret.push({
						showDate: showDate,
						dates: showDate,
						isWeekend: isWeekend,
						isCheckInDate: false,
						isCheckOutDate: false,
						isRestDay: isRestDay,
						isShow: false // 是否显示 库存和价格，对应样式 InRange
					})
				}
				return ret
			},
			createTemp(num) {
				let todayData = new Date(this.now)
				let thisYear = todayData.getFullYear()
				let thisMonth = todayData.getMonth() + 1
				let temp = []
				for (let i = 0; i < num; i++) {
					if (thisMonth > 12) {
						thisYear += 1
						thisMonth = 1
					}
					temp[i] = {
						year: thisYear,
						month: thisMonth,
						date: this.getMonthData(thisYear, thisMonth)
					}
					thisMonth += 1
				}
				return temp
			},
			createRange(num) {
				let rangs = []
				if (this.rangeObj.start && this.rangeObj.end) {
					// 引入日态之后已废弃
					let currentDate = new Date(this.rangeObj.start.replace(/-/gm, '/'))
					let endDate = new Date(this.rangeObj.end.replace(/-/gm, '/'))
					while (currentDate.getTime() <= endDate.getTime()) {
						rangs.push({
								date: moment(currentDate).format('YYYY-MM-DD'),
								type: 'ticket'
							} // 仅门票的日历不显示 库存等等
						)
						currentDate.setDate(currentDate.getDate() + 1)
					}
					this.isRange = true
				} else if (this.range.length > 0) {
					rangs = this.range
					this.isRange = true
				}
				this.rangs = rangs
			},
			getAllMonthData(num) {
				let temp = this.createTemp(num)
				this.createRange()
				if (this.isRange) {
					for (let i = 0; i < num; i++) {
						// 遍历每个月的日期
						temp[i].date.forEach(t => {
							t.isDisable = true
							t.isShow = false
							let date = temp[i].year + '-' + temp[i].month + '-' + t.showDate
							date = moment(date).format('YYYY-MM-DD')
							let current = moment().format('YYYY-MM-DD')
							this.rangs.forEach(tt => {
								if (tt.date === date &&tt.stock>0&& tt.date >= current) {
									t.isDisable = false
								}
								if (tt.date === date && tt.date >= current) {
                  console.log(t,tt)
									// 当前日期 属于 range里的日期，那么就需要展示 库存和价格
									t.isShow = true
									t.stock = tt.stock>tt.buyMaxNumber?tt.buyMaxNumber:tt.stock
									t.saleSettlementPrice = tt.saleSettlementPrice
									t.id = tt.id || ''
                  t.buyMaxNumber=tt.buyMaxNumber
                  t.buyMinNumber=tt.buyMinNumber
									if(this.inside.checkInDate === tt.date){
										this.inside.saleSettlementPrice = tt.saleSettlementPrice
										this.inside.stock = tt.stock>tt.buyMaxNumber?tt.buyMaxNumber:tt.stock
									}
								}
							})
						})
					}
				} else {
					// 如果 Info.startDate 是有值的，且不是时间区间的，这个startDate指的有效开始日期 - 门票
					let startDate = this.info.startDate ? this.info.startDate.split('-')[2] : ''
					startDate && (startDate = parseInt(startDate))
					// 第一个月今天之前的日期不可点击
					for (let i of temp[0].date) {
						let today = new Date(this.now)
						if ((i.showDate > today.getDate() || (i.showDate === today.getDate() && today.getHours() < 23))) {
							if (startDate) {
								if (i.showDate >= startDate) { // 日历上有效开始日期之后的时间可选
									break
								}
							} else {
								break
							}
						}
						i.isDisable = true
					}
				}
				this.allMonthData = temp
			},
			selectDate(month, day) {
        console.log(day)
				if (day.isDisable) {
					return
				}
				if (this.pattern === 'section') {
					if (this.checkInDate.date.isCheckInDate && this.checkOutDate.date.isCheckOutDate) {
						this.isCheckComplete = false
						this.checkInDate.date.isCheckInDate = false
						this.checkOutDate.date.isCheckOutDate = false
						day.isCheckInDate = true
						this.checkInDate = {
							date: day,
							month: month
						}
					} else if (this.checkInDate.date.isCheckInDate && !this.checkOutDate.date.isCheckOutDate) {
						// 判断点击是改变入住日期还是离店日期，年，年相等判断月，月相等判断日
						if (month.year > this.checkInDate.month.year || ((month.year === this.checkInDate.month.year) && (
								month.month > this.checkInDate.month.month)) || ((month.year === this.checkInDate.month
									.year) && (month.month === this.checkInDate.month.month) && day.showDate > this
								.checkInDate.date.showDate)) {
							this.isCheckComplete = false
							day.isCheckOutDate = true
							day.isCheckInDate = false
							this.checkOutDate = {
								date: day,
								month: month
							}
						} else {
							this.checkInDate.date.isCheckInDate = false
							day.isCheckInDate = true
							this.checkInDate = {
								date: day,
								month: month
							}
						}
					}
					if (this.checkInDate.date.isCheckInDate && this.checkOutDate.date.isCheckOutDate) {
						this.isCheckComplete = true
						this.inside.checkInDate = this.checkInDate.month.year + '-' + this.checkInDate.month.month + '-' +
							this.checkInDate.date.showDate
						this.inside.checkOutDate = this.checkOutDate.month.year + '-' + this.checkOutDate.month.month +
							'-' + this.checkOutDate.date.showDate
					}
				} else {
					this.isCheckComplete = false
					this.checkInDate.date.isCheckInDate = false
					day.isCheckInDate = true
					this.checkInDate = {
						date: day,
						month: month
					}
					let newMonth = month.month > 9 ? month.month : '0' + month.month
					let newDay = day.showDate > 9 ? day.showDate : '0' + day.showDate
          console.log(day)
					this.inside.checkInDate = month.year + '-' + newMonth + '-' + newDay
					this.inside.saleSettlementPrice = day.saleSettlementPrice
					this.inside.stock = day.stock
          this.inside.min = day.stock>day.buyMinNumber?day.buyMinNumber:day.stock
          this.inside.max = day.stock>day.buyMaxNumber?day.buyMaxNumber:day.stock
					this.$emit('choose-day', this.inside)
				}
			},
			changeMonth(month, index) {
        let date = ''
        if(month.month > 9) {
          date = month.year + '-' + month.month
          } else {
          date = month.year + '-' + '0' + month.month
        }
				this.$emit('chang-month', date)
				this.active = index
			}
		}
	}
</script>
<style lang="less" scoped>
	.calendar {
		border-radius: 20rpx 20rpx 0 0;

		.calendar-header {
			border-radius: 20rpx 20rpx 0 0;
			position: relative;
			width: 750upx;
			text-align: center;
			background-color: #fff;
			font-size: 34upx;
			color: #333333;
			font-weight: 600;
			padding: 20rpx 30rpx 0;
			display: flex;
			align-items: center;
			justify-content: flex-start;
			box-sizing: border-box;

			.headerTxt {
				height: 45rpx;
				font-size: 32rpx;
				font-family: PingFangSC-Medium, PingFang SC;
				font-weight: 500;
				color: #333333;
				line-height: 45rpx;
				margin-right: 27rpx;
			}

			.headerDate {
				height: 42rpx;
				font-size: 30rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #333333;
				line-height: 42rpx;
			}
		}

		.month {
			position: relative;
			width: 750upx;
			display: flex;
			background-color: #ffffff;
			height: 100upx;
			line-height: 100upx;
			border-bottom: 1upx solid #EFEFEF;
			margin-top:40upx;
			.week-day {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				.month-text {
					font-size: 30rpx;
					font-family: PingFang-SC-Medium, PingFang-SC;
					font-weight: 500;
					line-height: 42rpx;
					color: #333;
				}

				.price {
					height: 30rpx;
					line-height: 30rpx;
					font-size: 22rpx;
					margin-top: 2rpx;
					color: #999;
				}

				&.active {
					position: relative;

					.month-text,
					.price {
						color: #2064E1;
					}

					&::after {
						position: absolute;
						bottom: 0;
						left: 50%;
						transform: translateX(-50%);
						width: 150rpx;
						height: 2rpx;
						background: #2064E1;
						border-radius: 100rpx 100rpx 0px 0px;
						content: "";
					}
				}
			}
		}

		.week {
			position: relative;
			width: 750upx;
			display: flex;
			background-color: #ffffff;
			height: 80upx;
			line-height: 80upx;
			border-bottom: 1upx solid #EFEFEF;

			.week-day {
				flex: 1;
				color: #333;
				font-size: 30upx;
				font-weight: 400;
				text-align: center;
			}

			.weekend-day {
				font-size: 30rpx;
				font-family: PingFang-SC-Medium, PingFang-SC;
				font-weight: 400;
				color: #FF9E51;
			}
		}

		.blank {
			margin-top: 94upx;
		}

		.calendar-content {
			position: relative;
			width: 100%;
			max-width: 750upx;
			overflow: hidden;
			font-size: 24upx;
			height: 886upx;

			.scroll-Y {
				height: 8538upx;
			}

			.calendar-content-item {
				padding-top: 20rpx;

				.calendar-content-title {
					width: 100%;
					text-align: center;
					height: 92.25upx;
					line-height: 92.25upx;
					font-size: 27upx;
					font-weight: 600;
					letter-spacing: 3upx;
					border-bottom: 1upx solid #e5e5e5;
					background-color: #fff;
				}

				.calendar-content-day {
					background: #ffffff;
					overflow: hidden;

					&:last-of-type {
						margin-bottom: 335upx;
					}

					.holiday {
						color: #F28300;
					}

					.day-item {
						position: relative;
						float: left;
						width: 90rpx;
						height: 120rpx;
						border-radius: 10rpx;
						color: #333333;
						font-weight: 500;
						font-family: SFUIDisplay-Medium, SFUIDisplay;
						text-align: center;
						box-sizing: border-box;
						margin: 0 8rpx;

						&.lasts {
							border-bottom-width: 0upx;
						}

						.day-item-content {
							box-sizing: border-box;
							font-size: 30upx;
							line-height: 43.5upx;
							width: 100%;
							height: 100%;
							display: flex;
							align-items: center;
							justify-content: flex-start;
							flex-direction: column;
							padding-top: 8rpx;
							border: 2rpx solid transparent;

							.day-item-stock {
								font-size: 22rpx;
								line-height: 30rpx;
								color: #909498;
							}

							.day-item-num {
								color: #333333;
								line-height: 34rpx;
								margin: 0 0 4rpx;
								font-size: 28upx;
							}
						}

						.InRange {
							.day-item-num {
								color: #333;
								line-height: 34rpx;
							}

							.day-item-price {
								display: block;
								height: 30upx;
								line-height: 30upx;
								font-size: 22rpx;
								width: 100%;
								font-family: PingFangSC-Regular, PingFang SC;
								font-weight: 400;
								color: #909498;
								word-break: break-all;
							}

							.day-item-left {
								display: block;
								height: 20.25upx;
								line-height: 20.25upx;
								font-size: 24upx;
								width: 100%;
								color: #555;
							}
						}

						.CheckInDate,
						.CheckOutDate {
							background: #2064E1;
							overflow: hidden;

							.day-item-num,
							.day-item-price,
							.day-item-stock {
								color: #ffffff;
							}

							.day-item-num {
								line-height: 34rpx;
							}

							.day-item-price {
								margin-top: 4rpx;
								line-height: 30rpx;
							}
						}

						.CheckInDate {
							border-radius: 10upx 0 0 10upx;

							&.single {
								border-radius: 10upx;
								display: flex;
								align-items: center;
								justify-content: flex-start;
								flex-direction: column;
							}
						}

						.CheckOutDate {
							border-radius: 0 10upx 10upx 0;
						}

						.check-block {
							display: block;
							height: 30rpx;
							line-height: 30rpx;
							font-size: 24upx;
							color: #ff540b;
						}

						.restDay {
							position: absolute;
							top: 15upx;
							right: 0;
							font-size: 24upx;
							color: #fff;
						}
					}

					.scope {
						.day-item-content {
							background-color: rgba(255, 241, 176, .5);
						}

						.restDay {
							color: #484848;
						}
					}

					.disable {
						color: #D6D6D6;

						.day-item-content {
							.day-item-num {
								color: #D6D6D6;
							}
						}
					}
				}
			}
		}

		.calendar-foot {
			position: absolute;
			bottom: 0;
			width: 100%;
			background-color: #fff;
			height:170upx;
			border-top:1px #F1EFEE solid;
			// box-shadow: 0 -4upx 8upx 0 rgba(0, 0, 0, 0.07);
			// padding-bottom: calc(constant(safe-area-inset-bottom) - 34rpx) !important;
			// /* 兼容 iOS < 11.2 */
			// padding-bottom: calc(env(safe-area-inset-bottom) - 34rpx) !important;
			// /* 兼容 iOS >= 11.2 */
			display: flex;
			justify-content: space-between;
			padding:24upx 30upx 0 30upx;
			box-sizing: border-box;
			line-height: 40upx;
			.service {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				font-size: 22rpx;

				image {
					width: 48rpx;
					height: 48rpx;
					margin-bottom: 12rpx;
				}
			}

			.btn {
				text-align: center;
				width: 300upx;
				height: 82upx;
				line-height: 82upx;
				background: linear-gradient(135deg, #F78833 0%, #FFC77B 100%);
				border-radius: 40rpx;
				font-size: 28rpx;
				font-family: PingFangSC-Medium, PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
			}
		}
	}
</style>
